#include "table_window.h"
#include "table_item.h"
#include "game_window.h"
#include <QMessageBox>
#include "util.h"
TableWindow::TableWindow(QWidget *parent,const QString &user_name,const QString &url):QWidget(parent),SocketHelper(nullptr),TableHelper(nullptr),user_name_(user_name),url_(url)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setWindowTitle(QString("欢迎你,%1").arg(user_name_));

    resize(500,500);

    container = new QVBoxLayout(this);
    button_refresh = new QPushButton(this);
    button_refresh->setText(tr("刷新"));
    connect(button_refresh,&QPushButton::clicked,[=](bool){
        _send_server_info_message();
    });

    container->addWidget(button_refresh);

    table = new QListView(this);

    pModel = new QStandardItemModel(this);

    TableDelegate *pItemDelegate = new TableDelegate(this);
    connect(pItemDelegate,&TableDelegate::doubleClicked,this,&TableWindow::on_table_item_clicked);

    table->setItemDelegate(pItemDelegate);
    table->setModel(pModel);

    //不允许编辑，否则双击时会出来编辑框
    table-> setEditTriggers(QAbstractItemView::NoEditTriggers);

    container->addWidget(table);

    edit_input = new QLineEdit(this);
    connect(edit_input,&QLineEdit::returnPressed,this,std::bind(&TableWindow::on_send_clicked,this,false));

    button_send = new QPushButton(this);
    button_send->setText(tr("发送"));

    connect(button_send,&QPushButton::clicked,this,&TableWindow::on_send_clicked);

    label_chat = new QTextEdit(this);
    label_chat->setReadOnly(true);

    container->addWidget(label_chat,1);

    layout_chat = new QHBoxLayout();

    layout_chat->addWidget(edit_input,1);
    layout_chat->addWidget(button_send);

    container->addLayout(layout_chat);

    label_chat->setFixedHeight(70);

    init_connect();
}
void TableWindow::init_connect()
{

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&TableWindow::on_time_out);

    websocket = new QWebSocket(QString(),
                               QWebSocketProtocol::VersionLatest,
                               this);
    connect(websocket,&QWebSocket::connected,this,&TableWindow::on_connected);
    connect(websocket,&QWebSocket::disconnected,this,&TableWindow::on_disconnect);

    connect(websocket,&QWebSocket::textMessageReceived,this,static_cast<void (TableWindow::*)(const QString &)>(&TableWindow::on_message));
    QNetworkRequest req;
    req.setRawHeader(QString("user_name").toUtf8(),user_name_.toUtf8());
    req.setUrl(QUrl(url_));
    websocket->open(req);


}

void TableWindow::on_connected(){
    qDebug()<<"on_connected";

    TableHelper::on_connected();
    _send_server_info_message();
    if(timer)
    {
        timer->start(5000);
    }
}
void TableWindow::on_disconnect()
{
    qDebug()<<"on_disconnect";
    if(timer)
    {
        timer->stop();
    }
    TableHelper::on_disconnect();
    if(websocket)
    {
         QMessageBox::warning(this,"提示","连接异常");
         close();
    }
}

void TableWindow::on_send_clicked(bool)
{
    QString text = edit_input->text().trimmed();
    if(text.isEmpty())
    {
        return;
    }

    _send_chat_message(text);
    edit_input->clear();
}

void TableWindow::on_table_response_error(const int &code, const int &rep_code, const QString &rep_message, const QString &tag)
{
    QMessageBox::warning(this,"提示",rep_message);
}

void TableWindow::on_message(const QByteArray &message)
{
    TableHelper::on_message(message);
}

void TableWindow::on_message(const QString &message)
{
    TableHelper::on_message(message);
}

void TableWindow::on_chat_message(const ChatData &data)
{
    if(m_chat_content.length()>0)
    {
        m_chat_content.append('\n');
    }

    m_chat_content.append(format_unix_time(data.content.time));
    m_chat_content.append(data.name).append("说").append(':').append(data.content.message);

    label_chat->setText(m_chat_content);
    label_chat->moveCursor(QTextCursor::End);
}

void TableWindow::on_server_info_message(const QVector<TableItem> &data)
{
    QVector<TableItem>::const_iterator begin =  data.begin();
    QVector<TableItem>::const_iterator end = data.end();

    pModel->clear();
    while(begin!=end)
    {
        QStandardItem *pItem = new QStandardItem;
        const TableItem &itemData = *begin++;

        pItem->setData(QVariant::fromValue(itemData),Qt::UserRole);
        pModel->appendRow(pItem);
    }
}

void TableWindow::on_person_changed_notify(const PersonNotifyhData &d)
{
    int column_index =  d.action_params.index;
    int row_index = d.action_params.id-1;

    QStandardItem *item =   pModel->item(row_index);
    TableItem item_data =  item->data(Qt::UserRole).value<TableItem>();
    if(d.action_params.action)
    {
        //如果是进入牌桍
        item_data.users.replace(column_index,d.action_user);
    }
    else
    {
        UserInfo empty_user;
        empty_user.user_id=0;
        empty_user.name = "";
        item_data.users.replace(column_index,empty_user);
    }

    item->setData(QVariant::fromValue(item_data),Qt::UserRole);
}



void TableWindow::closeEvent(QCloseEvent *event)
{
    qDebug()<<"closeEvent";
    if(timer)
    {
        timer->stop();
        timer = nullptr;
    }
    if(websocket)
    {
        QWebSocket *ws = websocket;
        websocket = nullptr;
        ws->close();
    }
    QWidget::closeEvent(event);

}

void TableWindow::on_time_out()
{
    qDebug()<<"on_time_out";
    if(websocket&&websocket->isValid())
    {
        websocket->ping();
    }
}

TableWindow::~TableWindow()
{

}

void TableWindow::on_table_item_clicked(const QModelIndex &index, int position)
{
    QVariant v =  index.data(Qt::UserRole);
    TableItem item =  v.value<TableItem>();

    GameWindow *g_window = new GameWindow(this,websocket,item.id,position);
    g_window->show();
}
